import Bg from '@/assets/choise-bg.jpg';
import DrawButton from '@/assets/draw-1.png';
import Left1 from '@/assets/draw-100.png';
import Title from '@/assets/draw-2.png';
import Left2 from '@/assets/draw-99.png';
import PanDi from '@/assets/draw-pan-bottom.png';

import { debounce } from 'radash';

import { LuckyWheel } from '@lucky-canvas/react';
import { useRef, useState } from 'react';

import { PRIZE_IDS, Reward, RewardLog } from '@/apis/draw';
import { getUserInfo } from '@/apis/user';
import DrawBorder1 from '@/assets/draw-border-1.png';
import DrawBorder2 from '@/assets/draw-border-2.png';
import DrawBg from '@/assets/draw-pan-bg.png';
import DrawStartButton from '@/assets/draw-start-button.png';
import FixedButtons from '@/components/FixedButtons';
import { Toast } from 'react-vant';
import { useMutation, useQuery } from 'umi';
import useFail from './components/useFail';
import useSuccess from './components/useSuccess';

export default function Page() {
  const myLucky = useRef<any>(null);
  const { renderNode: renderFailNode, open: openFail } = useFail();
  const { renderNode: renderSuccessNode, open: openSuccess } = useSuccess();

  const [loading, setLoading] = useState<boolean>(false);

  const [blocks] = useState([
    {
      imgs: [
        {
          src: DrawBg,
          width: '100%',
          height: '100%',
          rotate: true,
        },
      ],
    },
  ]);
  const [prizes] = useState([
    { id: PRIZE_IDS.盲盒, name: '盲盒' },
    {
      id: 999,
      name: '再来一次',
    },
    {
      id: PRIZE_IDS.背包,
      name: '背包',
    },
    { id: undefined, name: '谢谢参与' },
    { id: PRIZE_IDS.贴纸, name: '贴纸' },
    {
      id: 999,
      name: '再来一次',
    },
    { id: PRIZE_IDS.迪士尼门票, name: '迪士尼门票' },
    { id: undefined, name: '谢谢参与' },
  ]);

  const { data: user, refetch: refetchUser } = useQuery(['get:user'], () =>
    getUserInfo(),
  );

  // ?获取中奖记录
  const { refetch: refetchRecord } = useQuery(['get:reward:log'], () =>
    RewardLog(),
  );

  // ?抽奖接口
  const { mutateAsync: mutateRewardAsync, data: rewardRes } = useMutation({
    mutationFn: Reward,
  });

  async function handleStart() {
    if (loading) return;
    setLoading(true);
    const { id, lottery_result } = await mutateRewardAsync();
    refetchUser(); // ?点击抽奖之后，立即更新剩余抽奖次数
    myLucky.current?.play();

    // 中奖了
    if (id && lottery_result) {
      const index = prizes.findIndex((i) => i.id === lottery_result);
      if (index === -1) {
        myLucky.current?.stop(1);
        return Toast.fail('未匹配到奖品');
      }
      myLucky.current?.stop(index);
    } else {
      // ?没有中奖
      myLucky.current?.stop(7);
    }
  }

  return (
    <>
      <FixedButtons />
      <section
        className=" min-h-screen flex flex-col items-center bg-cover bg-center pt-[150px]"
        style={{
          backgroundImage: `url(${Bg})`,
        }}
      >
        <h1
          className="w-[500px] h-[179px] bg-cover ml-[40px]"
          style={{
            backgroundImage: `url(${Title})`,
          }}
        />

        {/* left */}
        <div className="flex items-center leading-none text-white mt-4">
          <h1
            className="w-[275px] h-[38px] bg-cover"
            style={{ backgroundImage: `url(${Left1})` }}
          ></h1>
          <b className="mx-1 text-2xl">{user?.left_cj || 0}</b>
          <h1
            className="w-[37px] h-[38px] bg-cover"
            style={{ backgroundImage: `url(${Left2})` }}
          ></h1>
        </div>

        <div className=" relative w-[280PX] h-[280PX] mt-4">
          {/* start button  */}
          <button
            onClick={debounce({ delay: 200 }, handleStart)}
            className="w-[100PX] h-[100PX]  bg-contain bg-no-repeat absolute left-[34.2%] top-[31%] z-10"
            style={{ backgroundImage: `url(${DrawStartButton})` }}
          ></button>

          <i
            className=" absolute left-0 top-0 right-0 bottom-0 bg-cover"
            style={{ backgroundImage: `url(${DrawBorder1})` }}
          />
          <i
            className=" absolute left-0 top-0 right-0 bottom-0 bg-cover"
            style={{ backgroundImage: `url(${DrawBorder2})` }}
          />
          <LuckyWheel
            ref={myLucky}
            width="280px"
            height="280px"
            blocks={blocks}
            prizes={prizes}
            onStart={async () => {
              handleStart();
            }}
            onEnd={(prize: { id: undefined | number; name: string }) => {
              if (prize.id === undefined) {
                setTimeout(() => {
                  openFail();
                }, 800);
                return;
              }

              // ?中奖后， 把奖品ID和记录ID给组件
              setTimeout(() => {
                prize.id && rewardRes?.id && openSuccess(rewardRes?.id);
              }, 800);

              refetchUser();
              refetchRecord();
              setLoading(false);
            }}
          />
        </div>
        <div
          className="w-[410px] h-[110px] bg-cover -mt-[50px]"
          style={{
            backgroundImage: `url(${PanDi})`,
          }}
        ></div>

        {/* button */}
        <button
          onClick={() => handleStart()}
          className=" w-[246px] h-[90px] bg-cover active:scale-95 mt-12  animate-scales"
          style={{
            backgroundImage: `url(${DrawButton})`,
          }}
        />
      </section>

      {renderFailNode()}
      {renderSuccessNode()}
    </>
  );
}
